package cn.jingyuan.swan.gw.web.filter.zuul;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.core.Ordered;

import java.util.concurrent.TimeUnit;

/**
 * Zuul filter：guava -> RateLimiter
 */
@Slf4j
public class ZuulLimitGuavaFilter extends ZuulFilter {

    final RateLimiter rateLimiter = RateLimiter.create(5);

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return Ordered.HIGHEST_PRECEDENCE - 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        if (log.isDebugEnabled()) {
            log.debug(this.getClass().getSimpleName() + " execute before");
        }

        if (rateLimiter.tryAcquire(50, TimeUnit.MILLISECONDS)) {

        } else {

        }

        if (log.isDebugEnabled()) {
            log.debug(this.getClass().getSimpleName() + " execute end");
        }

        return null;
    }

}
